const myRequest = require('../../tool/myRequest')
const daoUser = require('../../dao/daoUser')
const cheerio = require('cheerio');

// 解析每一话里面的图片地址信息，并保存到数据库
function xxx(id = '', url = '') {
  url = url || 'http://localhost:8422/pages/test.html';
  // console.log(`id,url`, id, url)
  myRequest(url, {}).then(d => {
    if (d.status == 200) {
      const $ = cheerio.load(d.data);
      let is = $('img.content-img');
      if (is.length == 0) { console.log(`==*****=====没有找到对应的目标====***===1`, id, url); errrrrr++; return };
      let s = [];
      let noHasBaseUrl = 0;
      is.each(function (num) {
        let uu = $(this).attr('data-r-src')
        // console.log(uu, exportsObject.replaceUrl(uu))
        let rep = exportsObject.replaceUrl(uu);
        if (!rep.has) { noHasBaseUrl++; console.log(`====-noHasBaseUrl = `, id, url) }
        s.push(`('${id}_${num}', ${num}, '${rep.url}', '${id}', ${rep.base_url_id})`)
      })
      if (s.length > 0 && id && noHasBaseUrl == 0) {
        s = s.join(',');
        daoUser.addImgs([s]).then(d => {
          // console.log(`addImgs==== ok ==--=`, id,);
          daoUser.updateChapter_is_save_img([id, 1]).then(d => {
            // console.log(`updateChapter_is_save_img == ok ==--=`, id,)
            // errrrrr--;
            okkk++
            console.log(`=====`, '请求数：', startIndex_, '异常：', errrrrr, '成功：', okkk, id, url)
          }).catch(e => { console.log(`updateChapter_is_save_img`, id, e); errrrrr++; })
        }).catch(e => { console.log(`addImgs`, id, e); errrrrr++; })
      } else { errrrrr++; }
      // console.log(`s`, s)
    } else { console.log(`请求失败`, id, url, d.status); errrrrr++; }
  }).catch(e => { console.log(`e2`, id, url, e.message); errrrrr++ })
}
// xxx()

let url_long_to_small = []; // 从长到短的基础url
let base_url_id_Obj = {};
let errrrrr = 0;
let okkk = 0;
let startIndex, startIndex_ = 0;

let exportsObject = {
  getImgSrc(option = { time: 0.5 }) {
    let n = 0; let c = 0; let errornul = 0;
    daoUser.getBase_url().then(d => {
      d.forEach(element => { base_url_id_Obj[element.base_url_id] = element.base_url; });
      url_long_to_small = d;
      url_long_to_small.sort((a, b) => b.base_url.length - a.base_url.length);
      // console.log(url_long_to_small, base_url_id_Obj)

      daoUser.getChapterFormIs_save_img(errrrrr, 1000).then(d => {
        // console.log(`d`, d, d.length)
        // if (d.length <= 0) return;
        startIndex = 0,
          l = 15; // 每次请求多少个
        let jijdifje = setInterval(() => {
          let el = startIndex + l;
          for (let index = startIndex; index < el; index++) {
            if (d.length <= index) {
              clearInterval(jijdifje),
                console.log(`close =  = = 重新开始`,);
              setTimeout(() => { exportsObject.getImgSrc() }, 3000);
              return;
            }
            const element = d[index];
            xxx(element.id, element.base_url + element.chapter_url);
            startIndex_++;
            // console.log(index, element.id, element.base_url + element.chapter_url);
          }
          startIndex += l;
        }, 1000 * option.time);
      })

    })
  },
  replaceUrl(url = '') {
    // console.log(`url_long_to_small`, url_long_to_small)
    for (let index = 0; index < url_long_to_small.length; index++) {
      const element = url_long_to_small[index];
      if (url.includes(element.base_url)) {
        return {
          url: url.replace(element.base_url, ''),
          base_url_id: element.base_url_id,
          has: true
        }
      }
    }
    return { has: false }
  }
}

module.exports = exportsObject;

